package cn.dansj.service.Impl;

import cn.dansj.entity.WebCollect;
import cn.dansj.repository.WebCollectRepository;
import cn.dansj.service.WebCollectService;
import cn.dansj.common.utils.transfer.Transformation;
import cn.dansj.common.utils.transfer.Verification;
import jakarta.persistence.criteria.Predicate;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class WebCollectServiceImpl implements WebCollectService {
    private final WebCollectRepository webCollectRepository;

    public WebCollectServiceImpl(WebCollectRepository webCollectRepository) {
        this.webCollectRepository = webCollectRepository;
    }

    @Override
    public Page<WebCollect> search(Integer pageNum, Integer pageLimit, String url) {
        Specification<WebCollect> webCollectSpecification = (root, criteriaQuery, criteriaBuilder) -> {
            List<Predicate> paramsList = new ArrayList<>();
            if (Verification.checkNotNull(url)) {
                paramsList.add(criteriaBuilder.like(criteriaBuilder.lower(root.get("url")), Transformation.sqlLikeToLowCase(url)));
            }
            Predicate[] predicates = new Predicate[paramsList.size()];
            return criteriaBuilder.and(paramsList.toArray(predicates));
        };

        Sort sort = Sort.by(Sort.Direction.DESC, "crtTime");
        Pageable pageable = PageRequest.of(pageNum - 1, pageLimit, sort);
        return webCollectRepository.findAll(webCollectSpecification, pageable);
    }

    @Override
    public void save(WebCollect webCollect) {
        webCollectRepository.save(webCollect);
    }

    @Override
    @Transactional
    public void delete(String sequence) {
        webCollectRepository.deleteById(sequence);
    }

    @Override
    public List<WebCollect> getAllData() {
        return webCollectRepository.getAll();
    }
}
